const axios = require('axios');
const wxConfig = require('../../../config/wxapi.json');
const cache = require('../../module/tool/cache');
const WxApiError = require('../../module/error/wxapierror');

async function getWxAPIAccessToken () {
    let ak = await cache.readCache('wxAssessToken');
    if (!ak) {
        const appId = wxConfig.secret.appId;
        const appSecret = wxConfig.secret.appSecret;
        let res = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`);
        let token = res.data;
        if (!token.access_token) {
            throw new WxApiError.AssessTokenRequireError('微信接口凭证请求失败!');
        }
        ak = token.access_token;
        await cache.writeCache('wxAssessToken', ak, token.expires_in);
    }
    return ak;
}

module.exports = {
    getWxAPIAccessToken
};
